package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    public OrderSubmitVO submit( OrdersSubmitDTO ordersSubmitDTO) {
        //判断用户订单地址是否为空和用户购物车数据是否为空,抛出服务异常
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new RuntimeException("用户地址为空");
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.getByShoppingCart(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new RuntimeException("用户购物车为空");
        }
        //向订单表添加1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //一般使用时间戳作为订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        ordersMapper.add(orders);

        //向订单明细表添加n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);

        }
        orderDetailMapper.addBatch(orderDetails);
        //请空购物车
        shoppingCartMapper.cleanAll(BaseContext.getCurrentId());
        /*
        向商家推送待接单的消息
        * */
        //通过WebSocketServer发送消息给客户端type orderId content
        Map map = new HashMap();
        map.put("type",1);//1表示来单提醒,2表示客户催单
        map.put("orderId",orders.getId());//add方法中已经设置了主键返回
        map.put("content","订单号:"+orders.getNumber());
        //将map转为json
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);


        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();



    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    @Override
    public PageResult page(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        Page<Orders> page1 = (Page<Orders>) ordersMapper.page(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (page1 != null && page1.getTotal() > 0) {
            for (Orders orders : page1) {
                Long orderId = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOerderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        return  new PageResult(page1.getTotal(), list);

    }

    @Override
    public OrderVO show(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = ordersMapper.getById(id);
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOerderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        orderVO.setOrderDishes(orderDetailList.stream().map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber()).collect(Collectors.joining(",")));
        return orderVO;
    }

    @Override
    public void cancel(Long id) {
       Orders orders = ordersMapper.getById(id);
       if (orders == null) {
           throw new RuntimeException("订单不存在");
       }
       if (orders.getStatus() > 2) {
           throw new RuntimeException("订单不能取消");
       }
       Orders orders1 = new Orders();
       orders1.setId(id);
       orders1.setStatus(Orders.CANCELLED);
       orders1.setCancelReason("用户取消");
       orders1.setCancelTime(LocalDateTime.now());
       ordersMapper.update(orders1);
    }

    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOerderId(id);
        List<ShoppingCart> carts = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, cart);
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            return cart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insertBatch(carts);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        int page = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();
        PageHelper.startPage(page, pageSize);
        List<Orders> list = ordersMapper.page(ordersPageQueryDTO);
        Page<Orders> page1 = (Page<Orders>)list;

        return  new PageResult(page1.getTotal(), list);
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        LocalDateTime confirmTime = LocalDateTime.now();
        ordersMapper.confirm(ordersConfirmDTO);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        ordersMapper.rejection(ordersRejectionDTO);
    }

    @Override
    public void delivery(Long id) {

        LocalDateTime deliveryTime = LocalDateTime.now();
        ordersMapper.delivery(id,deliveryTime);
    }

    @Override
    public void complete(Long id) {
        LocalDateTime completeTime = LocalDateTime.now();
        ordersMapper.complete(id,completeTime);
    }

    @Override
    public void admiinCancel(OrdersCancelDTO ordersCancelDTO) {
        LocalDateTime cancelTime = LocalDateTime.now();
        ordersMapper.admincancel(ordersCancelDTO,cancelTime);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;

    }

    @Override
    public void reminder(Long id) {
        Map map = new HashMap();
        Orders orderDB = ordersMapper.getById(id);
        if (orderDB == null) {
            throw new RuntimeException("订单错误");
        }
        map.put("type",2);
        map.put("orderId", orderDB.getId());
        map.put("content", "订单号：" + orderDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
